<template>
  <div class="portfolio-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>组合产品管理</h2>
          <el-button type="primary" @click="$router.push('/portfolio-management/create')">创建组合</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-container">
        <el-form :inline="true" class="search-form">
          <el-form-item label="组合名称">
            <el-input v-model="searchForm.name" placeholder="输入组合名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="策略名称">
            <el-select v-model="searchForm.strategy" placeholder="选择策略" clearable>
              <el-option
                v-for="strategy in strategies"
                :key="strategy.id"
                :label="strategy.name"
                :value="strategy.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 组合表格 -->
      <el-table :data="filteredPortfolios" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="组合名称" width="150"></el-table-column>
        <el-table-column prop="strategy" label="策略名称" width="150"></el-table-column>
        <el-table-column label="包含基金" width="200">
          <template #default="scope">
            <el-popover
              placement="right"
              :width="300"
              trigger="hover">
              <template #reference>
                <div>{{ scope.row.funds && scope.row.funds.length ? scope.row.funds.length + '只基金' : '无基金' }}</div>
              </template>
              <div v-if="scope.row.funds && scope.row.funds.length">
                <div v-for="(fund, index) in scope.row.funds" :key="index" class="fund-item">
                  {{ fund }} ({{ scope.row.weights && scope.row.weights[index] ? (scope.row.weights[index] * 100).toFixed(0) : 0 }}%)
                </div>
              </div>
              <div v-else>
                该组合尚未添加基金
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建者" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="120"></el-table-column>
        <el-table-column label="收益表现" width="120">
          <template #default="scope">
            <span :class="{ 'red-text': scope.row.performance > 0, 'green-text': scope.row.performance < 0 }">
              {{ scope.row.performance !== undefined ? (scope.row.performance * 100).toFixed(2) + '%' : '暂无数据' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template #default="scope">
            <el-button size="small" @click="viewPortfolioDetail(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="editPortfolio(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deletePortfolio(scope.$index)">删除</el-button>
            <el-button size="small" type="success" @click="createTrade(scope.row)">交易</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 组合详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="组合详情"
      width="800px">
      <div v-if="currentPortfolio">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="组合名称">{{ currentPortfolio.name }}</el-descriptions-item>
          <el-descriptions-item label="策略名称">{{ currentPortfolio.strategy }}</el-descriptions-item>
          <el-descriptions-item label="创建者">{{ currentPortfolio.creator }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentPortfolio.createTime }}</el-descriptions-item>
          <el-descriptions-item label="收益表现">
            <span :class="{ 'red-text': currentPortfolio.performance > 0, 'green-text': currentPortfolio.performance < 0 }">
              {{ currentPortfolio.performance !== undefined ? (currentPortfolio.performance * 100).toFixed(2) + '%' : '暂无数据' }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="portfolio-composition" style="margin-top: 20px;">
          <h3>组合构成</h3>
          <el-table :data="portfolioComposition" style="width: 100%" border v-if="currentPortfolio.funds && currentPortfolio.funds.length">
            <el-table-column prop="fund" label="基金名称" width="180"></el-table-column>
            <el-table-column prop="weight" label="权重">
              <template #default="scope">
                {{ (scope.row.weight * 100).toFixed(0) }}%
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="该组合尚未添加基金"></el-empty>
        </div>
        
        <div class="portfolio-performance" style="margin-top: 20px;">
          <h3>收益走势</h3>
          <div class="chart-placeholder" style="height: 300px;">
            <el-empty description="组合收益走势图将在此显示"></el-empty>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'PortfolioManagement',
  setup() {
    const store = useStore()
    const router = useRouter()
    const detailDialogVisible = ref(false)
    const currentPortfolio = ref(null)
    
    // 搜索表单
    const searchForm = reactive({
      name: '',
      strategy: '',
      dateRange: []
    })
    
    // 计算属性：获取策略列表
    const strategies = computed(() => {
      return store.getters.getStrategies
    })
    
    // 计算属性：获取过滤后的组合列表
    const filteredPortfolios = computed(() => {
      return store.getters.getPortfolios.filter(portfolio => {
        // 名称过滤
        const nameMatch = !searchForm.name || portfolio.name.includes(searchForm.name)
        
        // 策略过滤
        const strategyMatch = !searchForm.strategy || portfolio.strategy === searchForm.strategy
        
        // 日期过滤
        let dateMatch = true
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          const startDate = searchForm.dateRange[0]
          const endDate = searchForm.dateRange[1]
          const createDate = portfolio.createTime
          dateMatch = createDate >= startDate && createDate <= endDate
        }
        
        return nameMatch && strategyMatch && dateMatch
      })
    })
    
    // 计算属性：获取当前组合的构成
    const portfolioComposition = computed(() => {
      if (!currentPortfolio.value) return []
      if (!currentPortfolio.value.funds || !currentPortfolio.value.weights) return []
      
      return currentPortfolio.value.funds.map((fund, index) => ({
        fund,
        weight: currentPortfolio.value.weights[index] || 0
      }))
    })
    
    // 生命周期钩子
    onMounted(() => {
      store.dispatch('loadPortfolios')
      store.dispatch('loadStrategies')
    })
    
    // 方法：搜索组合
    const handleSearch = () => {
      // 搜索逻辑由 filteredPortfolios 计算属性处理
    }
    
    // 方法：重置搜索
    const resetSearch = () => {
      searchForm.name = ''
      searchForm.strategy = ''
      searchForm.dateRange = []
    }
    
    // 方法：查看组合详情
    const viewPortfolioDetail = (portfolio) => {
      currentPortfolio.value = portfolio
      detailDialogVisible.value = true
    }
    
    // 方法：编辑组合
    const editPortfolio = (portfolio) => {
      router.push({
        path: '/portfolio-management/create',
        query: { id: portfolio.id, mode: 'edit' }
      })
    }
    
    // 方法：删除组合
    const deletePortfolio = (index) => {
      const portfolio = filteredPortfolios.value[index];
      ElMessageBox.confirm('确定要删除该组合吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('removePortfolio', portfolio.id).then(() => {
          ElMessage.success('删除成功');
        }).catch(error => {
          ElMessage.error('删除失败: ' + error.message);
        });
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 方法：创建交易
    const createTrade = (portfolio) => {
      router.push({
        path: '/trade-management/create',
        query: { portfolioId: portfolio.id }
      })
    }
    
    return {
      searchForm,
      detailDialogVisible,
      currentPortfolio,
      strategies,
      filteredPortfolios,
      portfolioComposition,
      handleSearch,
      resetSearch,
      viewPortfolioDetail,
      editPortfolio,
      deletePortfolio,
      createTrade
    }
  }
}
</script>

<style scoped>
.portfolio-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
}

.red-text {
  color: #f56c6c;
}

.green-text {
  color: #67c23a;
}

.fund-item {
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #eee;
}

.fund-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.chart-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}
</style> 